import { memo, useMemo } from 'react';
import { Outlet, useLocation } from 'react-router-dom';
import classnames from 'classnames';

import { useRecoilValue } from 'recoil';
import { collapsedState, globalState } from '@/store/global';
import { useI18n } from '@/store/i18n';
import locales from './UniversalLayout/locales';

import { formatRoutes } from '@/utils/router';

import Permission from '@/components/Permission';
import SliderBar from './components/SliderBar';
import LayoutHeader from './components/Header';
import RightFooter from './UniversalLayout/components/RightFooter';
import RightPanel from './components/RightPanel';

import { MenuRoutes as layoutRotes } from '@/router';

import useTitle from '@/hooks/useTitle';

import './css/index.less';
import { Layout } from 'antd';

import { CSSTransition, TransitionGroup } from 'react-transition-group';
import Settings from './components/Settings';

const { Footer, Content } = Layout;

export default memo(() => {
  const location = useLocation();
  console.log('layout render');
  const collapsed = useRecoilValue(collapsedState);

  // 框架所有菜单路由 与 patch key格式的所有菜单路由
  const routerPathKeyRouter = useMemo(() => formatRoutes(JSON.parse(JSON.stringify(layoutRotes))), []);

  // 当前路由item
  const routeItem = useMemo(() => routerPathKeyRouter.pathKeyRouter[location.pathname], [location]);

  // 设置title
  const t = useRecoilValue(useI18n(locales));
  useTitle(t(routeItem?.meta?.title || ''));

  return (
    <Layout className={classnames('layout', { hideSidebar: collapsed })}>
      <SliderBar routerPathKeyRouter={routerPathKeyRouter} routeItem={routeItem} />
      <Layout className='main-container right-layout'>
        <LayoutHeader routerPathKeyRouter={routerPathKeyRouter} routeItem={routeItem}></LayoutHeader>

        <Content className='app-container'>
          <Permission role={routeItem?.meta?.roles}>
            <TransitionGroup>
              <CSSTransition key={location.pathname} timeout={500} classNames='fade' exit={false}>
                <Outlet />
              </CSSTransition>
            </TransitionGroup>
          </Permission>
        </Content>
        <RightPanel>
          <Settings />
        </RightPanel>
        <Footer style={{ textAlign: 'center' }}>
          <RightFooter />
        </Footer>
      </Layout>
    </Layout>
  );
});
